package Dao;

import Model.User;
import Utils.DBUtils;

import java.sql.*;

/**
 * @author zyp
 * date 2022-03-08
 */
public class UserDaoImpl implements UserDao {

    @Override
    public int addUser(User user) {
        Connection connection = DBUtils.getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String sql = "insert into user values(null,?,?,?,1)";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getSalt());
            preparedStatement.setString(3, user.getPassword());

            int rows = preparedStatement.executeUpdate();
            resultSet = preparedStatement.getGeneratedKeys();
            while (resultSet.next()) {
                System.out.println(resultSet.getInt(1));
            }
            if (rows == 1) {
                connection.commit();
                return rows;
            } else {
                connection.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return 0;
    }

    @Override
    public User findUserByUsername(User user) {
        User selectedUser = new User();

        Connection connection = DBUtils.getConnection();
        String sql = "select * from user where user.username = ?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, user.getUsername());
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                selectedUser.setId(resultSet.getInt("id"));
                selectedUser.setUsername(resultSet.getString("username"));
                selectedUser.setPassword(resultSet.getString("password"));
                selectedUser.setSalt(resultSet.getString("salt"));
                selectedUser.setStatus(resultSet.getInt("status"));
            }

            return selectedUser;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
}
